package com.it.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.dao.BlogTagMapper;
import com.it.domain.BlogTagEntity;
import com.it.exception.NotFoundException;
import com.it.service.BlogTagService;
import com.it.util.PageUtils;
import com.it.util.Query;
import org.springframework.beans.BeanUtils;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : code1997
 * @date : 2021/9/9 22:46
 */
@Service
public class BlogTagServiceImpl extends ServiceImpl<BlogTagMapper, BlogTagEntity> implements BlogTagService {


    @Transactional
    @Override
    public BlogTagEntity saveTag(BlogTagEntity blogTagEntity) {
        this.baseMapper.insert(blogTagEntity);
        return blogTagEntity;
    }

    @Transactional
    @Override
    public BlogTagEntity getTag(Long id) {
        return this.baseMapper.selectById(id);
    }

    @Transactional
    @Override
    public PageUtils listTag(Map<String, Object> params) {
        return new PageUtils(this.page(new Query<BlogTagEntity>().getPage(params,"id",false), new QueryWrapper<>()));
    }

    @Transactional
    @Override
    public BlogTagEntity updateTag(Long id, BlogTagEntity blogTagEntity) {
        BlogTagEntity tempBlogTagEntity = this.baseMapper.selectById(id);
        if (tempBlogTagEntity == null) {
            throw new NotFoundException("该标签不存在！更新失败！！！");
        }
        BeanUtils.copyProperties(blogTagEntity, tempBlogTagEntity);
        this.baseMapper.updateById(blogTagEntity);
        return blogTagEntity;
    }

    /**
     * todo：listTagTop
     */
    @Override
    public List<BlogTagEntity> listTagTop(Integer size) {
        return this.baseMapper.listTagTop(size);
    }

    @Transactional
    @Override
    public void deleteTag(Long id) {
        this.baseMapper.deleteById(id);
    }

    @Transactional
    @Override
    public BlogTagEntity getTagByName(String name) {
        return this.baseMapper.selectOne(new QueryWrapper<BlogTagEntity>().eq("name", name));
    }

    @Override
    public List<BlogTagEntity> listTag() {
        return this.baseMapper.selectList(new QueryWrapper<>());
    }

    /**
     * 未知正确性！！！
     * 可以实现功能再新增或者修改博客的页面进行标签的增加
     */
    @Override
    public List<BlogTagEntity> listTag(String ids) {
        if (ids != null && ids.trim().length() > 0) {
            return this.baseMapper.selectBatchIds(Arrays.stream(ids.split(",")).collect(Collectors.toSet()));
        }
        throw new NotFoundException("没找到");
    }

}
